from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 打开Chrome浏览器
driver = webdriver.Chrome()

# 导航到登录页面
driver.get("https://the-internet.herokuapp.com/login")

# 输入有效的用户名和密码
username_input = driver.find_element(By.ID, "username")
password_input = driver.find_element(By.ID, "password")
username_input.send_keys("tomsmith")
password_input.send_keys("SuperSecretPassword!")
password_input.send_keys(Keys.RETURN)

# 等待重定向到首页并验证用户名
WebDriverWait(driver, 10).until(EC.url_to_be("https://the-internet.herokuapp.com/secure"))
assert "Welcome to the Secure Area" in driver.page_source
# assert "tomsmith" in driver.page_source
if "tomsmith" in driver.page_source:
    print("用户名显示在了主页上")
else:
    print("用户名没有显示在主页上")


# 退出登录并验证重定向到登录页面
driver.find_element(By.CSS_SELECTOR, ".button.secondary.radius").click()
WebDriverWait(driver, 10).until(EC.url_to_be("https://the-internet.herokuapp.com/login"))
assert "Login Page" in driver.page_source

# 输入无效的用户名和密码并验证错误消息
username_input = driver.find_element(By.ID, "username")
password_input = driver.find_element(By.ID, "password")
username_input.send_keys("invalidusername")
password_input.send_keys("invalidpassword")
password_input.send_keys(Keys.RETURN)

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".flash.error")))
# assert "Your username is invalid!" in driver.page_source
# assert "Your password is invalid!" in driver.page_source
if "Your username is invalid!" in driver.page_source or "Your password is invalid!" in driver.page_source:
    print("用户名和密码错误")
else:
    print("用户名和密码正确")

# 关闭浏览器
driver.quit()
